// import ui from "./ui.js";
// import conf from "../../config.js"
let locale = {
    "Today": "今天",
    months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
    weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
    longDateFormat: {
      LT: 'HH:mm',
      LTS: 'HH:mm:ss',
      L: 'YYYY-MM-DD',
      LL: 'YYYY年MM月DD日',
      LLL: 'YYYY年MM月DD日Ah点mm分',
      LLLL: 'YYYY年MM月DD日ddddAh点mm分',
      l: 'YYYY-M-D',
      ll: 'YYYY年M月D日',
      lll: 'YYYY年M月D日 HH:mm',
      llll: 'YYYY年M月D日dddd HH:mm'
    },
    meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
    meridiemHour: function (hour, meridiem) {
      if (hour === 12) {
        hour = 0;
      }
      if (meridiem === '凌晨' || meridiem === '早上' ||
        meridiem === '上午') {
        return hour;
      } else if (meridiem === '下午' || meridiem === '晚上') {
        return hour + 12;
      } else {
        // '中午'
        return hour >= 11 ? hour : hour + 12;
      }
    },
    meridiem: function (hour, minute, isLower) {
      const hm = hour * 100 + minute;
      if (hm < 600) {
        return '凌晨';
      } else if (hm < 900) {
        return '早上';
      } else if (hm < 1130) {
        return '上午';
      } else if (hm < 1230) {
        return '中午';
      } else if (hm < 1800) {
        return '下午';
      } else {
        return '晚上';
      }
    },
    calendar: {
      sameDay: '[今天]LT',
      nextDay: '[明天]LT',
      nextWeek: '[下]ddddLT',
      lastDay: '[昨天]LT',
      lastWeek: '[上]ddddLT',
      sameElse: 'L'
    },
    dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
    ordinal: function (number, period) {
      switch (period) {
        case 'd':
        case 'D':
        case 'DDD':
          return number + '日';
        case 'M':
          return number + '月';
        case 'w':
        case 'W':
          return number + '周';
        default:
          return number;
      }
    },
    relativeTime: {
      future: '%s内',
      past: '%s前',
      s: '几秒',
      ss: '%d秒',
      m: '1分钟',
      mm: '%d分钟',
      h: '1小时',
      hh: '%d小时',
      d: '1天',
      dd: '%d天',
      M: '1个月',
      MM: '%d个月',
      y: '1年',
      yy: '%d年'
    },
    week: {
      // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
      dow: 1, // Monday is the first day of the week.
      doy: 4 // The week that contains Jan 4th is the first week of the year.
    }
  }
  
  let lang = {
    // placeholder: "请选择日期",
    // yearPlaceholder: "请选择年份",
    // quarterPlaceholder: "请选择季度",
    // monthPlaceholder: "请选择月份",
    // weekPlaceholder: "请选择周",
    rangePlaceholder: ["开始日期", "结束日期"],
    rangeYearPlaceholder: ["开始年份", "结束年份"],
    rangeMonthPlaceholder: ["开始月份", "结束月份"],
    rangeWeekPlaceholder: ["开始周", "结束周"],
    "placeholder": "请选择日期",
    "today": "今天",
    "yearFormat": "YYYY",
    "dateFormat": "M/D/YYYY",
    "dayFormat": "D",
    "dateTimeFormat": "M/D/YYYY HH:mm:ss",
    "monthFormat": "MMMM"
  }
  
  const typelist = [
    "亚黏土",
    "卵石",
    "块石",
    "填土",
    "漂石",
    "砂土",
    "砂浆",
    "粉土",
    "腐殖土",
    "软土",
    "辉岩",
    "黏土"
  ];
  
  var style_label = {
    opacity: 1,
    textAnchor: "center", // 文本相对锚点的位置 center|left|right|top|bottom|top-left
    textOffset: [0, 0], // 文本相对锚点的偏移量 [水平, 垂直]
    spacing: 2, // 字符间距
    // padding: [20, 20], // 文本包围盒 padding [水平，垂直]，影响碰撞检测结果，避免相邻文本靠的太近
    stroke: "000000", // 描边颜色
    strokeWidth: 0.3, // 描边宽度
    strokeOpacity: 1.0,
    // fontWeight: 'bold',
    fontFamily: "Microsoft YaHei"
  };
  async function fetch_sync(url) {
    const res = await fetch(url);
    const result = await res.json();
    return result;
  }
  async function getdict(tablename){
    return (await $.getJSON(`${url_webback}/api/metadata/${tablename}`)).fields;
  }
  
  async function getData(sql){
    return await $.post(
      url_webserver + "/system/projectinfo/anysql",
      {
        sql: sql }
    );
  }
  
  async function getData0(sql){
    return await $.post(
      url_webserver + "/system/projectinfo/anysql0",
      {
        sql: sql }
    );
  }
  let sqlpre = `SELECT
  EXPLOR_POINT.OBJECTID, 
  EXPLOR_POINT.explor_id, 
  EXPLOR_POINT.project_id, 
  EXPLOR_POINT.type, 
  EXPLOR_POINT.x, 
  EXPLOR_POINT.y, 
  EXPLOR_POINT.z, 
  EXPLOR_POINT.m, 
  EXPLOR_POINT.start_date, 
  EXPLOR_POINT.finish_date, 
  EXPLOR_POINT.dw, 
  EXPLOR_POINT.dw_date, 
  PROJECT_INFO.OBJECTID AS p_OBJECTID, 
  PROJECT_INFO.company_id, 
  PROJECT_INFO.id AS p_id, 
  PROJECT_INFO.name, 
  PROJECT_INFO.type AS p_type, 
  PROJECT_INFO.grade, 
  PROJECT_INFO.manager, 
  PROJECT_INFO.start_date AS p_start_date, 
  PROJECT_INFO.finish_date AS p_finish_date, 
  PROJECT_INFO.province, 
  PROJECT_INFO.city, 
  PROJECT_INFO.site, 
  PROJECT_INFO.coordinate, 
  PROJECT_INFO.elevation, 
  PROJECT_INFO.pga, 
  PROJECT_INFO.tg,
  EXPLOR_POINT.SHAPE.STX STX,
  EXPLOR_POINT.SHAPE.STY STY
  FROM
  EXPLOR_POINT,PROJECT_INFO`
  async function getExplors(where){
    return await $.post(
      url_webserver + "/system/projectinfo/anysql",
      {
        sql: encodeURI(`${sqlpre} where EXPLOR_POINT.project_id = PROJECT_INFO.project_id ${where?' and '+where:''}`) }
    );
  }
  
  async function post_async(url, data) {
    $.post(url, {
      dataType: "json",
      data: data,
      timeout: 5000,
      success: function(result) {
        if (result) {
          resolve(result);
        } else {
          reject(new Error("erro"));
        }
      },
      error: function() {
        reject(new Error("erro"));
      }
    });
  }

  function formatData_JSON(data) {
    var list_explor = [];
    data.features.forEach(element => {
      list_explor.push(element.attributes);
    });
    return list_explor;
  }
  
  function getFields_layer(data) {
    var fieldnames = ["layer_code", "depth_btm", "name", "type", "remark"];
    var fields = [];
    data.fields.forEach((field, idx) => {
      if (fieldnames.findIndex(x => x == field.name) >= 0)
        fields.push({
          dataIndex: field.name,
          title: field.alias,
          // width:50,
          // fixed:fields.length==0?'left':'',
          ellipsis: true
        });
    });
    fields.push(
      {
        title: "柱状图",
        key: "action",
        scopedSlots: { customRender: "action" }
      },
      {
        title: "详细",
        key: "shiyan",
        scopedSlots: { customRender: "shiyan" }
      }
    );
    return fields;
  }
  
  function getFields(data) {
    var fields = [];
    if(!data.fields)return fields;
    data.fields.forEach((field, idx) => {
      // if (fieldnames.findIndex(x => x == field.name) >= 0)
      fields.push({
        key: field.name,
        dataIndex: field.name,
        title: field.alias,
        width:150,
        // fixed:fields.length==0?'left':'',
        ellipsis: true
      });
    });
    return fields;
  }
  
  var osmcartourl =
    "https://cartodb-basemaps-{subDomain}.global.ssl.fastly.net/dark_all/{level}/{col}/{row}.png";
  var tdtsataddr =
    "http://{subDomain}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=067998e486ea7ea61c91442ec719e8b3";
  var tdtvecaddr =
    "http://{subDomain}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=067998e486ea7ea61c91442ec719e8b3";
  var tdtcvaaddr =
    "http://{subDomain}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=067998e486ea7ea61c91442ec719e8b3";
  
  var lods_tdt = [
    {
      level: 0,
      levelValue: "1",
      resolution: 78271.51696401063,
      scale: 2.958293554545284e8
    },
    {
      level: 1,
      levelValue: "2",
      resolution: 39135.758482005316,
      scale: 1.479146777272642e8
    },
    {
      level: 2,
      levelValue: "3",
      resolution: 19567.879241002658,
      scale: 7.39573388636321e7
    },
    {
      level: 3,
      levelValue: "4",
      resolution: 9783.939620501329,
      scale: 3.697866943181605e7
    },
    {
      level: 4,
      levelValue: "5",
      resolution: 4891.9698102506645,
      scale: 1.8489334715908024e7
    },
    {
      level: 5,
      levelValue: "6",
      resolution: 2445.9849051253323,
      scale: 9244667.357954012
    },
    {
      level: 6,
      levelValue: "7",
      resolution: 1222.9924525626661,
      scale: 4622333.678977006
    },
    {
      level: 7,
      levelValue: "8",
      resolution: 611.4962262813331,
      scale: 2311166.839488503
    },
    {
      level: 8,
      levelValue: "9",
      resolution: 305.74811314066653,
      scale: 1155583.4197442515
    },
    {
      level: 9,
      levelValue: "10",
      resolution: 152.87405657033327,
      scale: 577791.7098721258
    },
    {
      level: 10,
      levelValue: "11",
      resolution: 76.43702828516663,
      scale: 288895.8549360629
    },
    {
      level: 11,
      levelValue: "12",
      resolution: 38.21851414258332,
      scale: 144447.92746803144
    },
    {
      level: 12,
      levelValue: "13",
      resolution: 19.10925707129166,
      scale: 72223.96373401572
    },
    {
      level: 13,
      levelValue: "14",
      resolution: 9.55462853564583,
      scale: 36111.98186700786
    },
    {
      level: 14,
      levelValue: "15",
      resolution: 4.777314267822915,
      scale: 18055.99093350393
    },
    {
      level: 15,
      levelValue: "16",
      resolution: 2.3886571339114573,
      scale: 9027.995466751965
    },
    {
      level: 16,
      levelValue: "17",
      resolution: 1.1943285669557286,
      scale: 4513.9977333759825
    },
    {
      level: 17,
      levelValue: "18",
      resolution: 0.5971642834778643,
      scale: 2256.9988666879913
    },
    // { 
    //         "level": 18, 
    //       "levelValue": "19", 
    //       "resolution": 0.29858214173893216, 
    //       "scale": 1128.4994333439956 
    //  }
  ]; 
  var lods_arcgis_elevation = [
    {
      level: 0,
      levelValue: "1",
      resolution: 156543.03392800014,
      scale: 5.91657527591555e8
    },
    {
      level: 1,
      levelValue: "2",
      resolution: 78271.51696399994,
      scale: 2.95828763795777e8
    },
    {
      level: 2,
      levelValue: "3",
      resolution: 39135.75848200009,
      scale: 1.47914381897889e8
    },
    {
      level: 3,
      levelValue: "4",
      resolution: 19567.87924099992,
      scale: 7.3957190948944e7
    },
    {
      level: 4,
      levelValue: "5",
      resolution: 9783.93962049996,
      scale: 3.6978595474472e7
    },
    {
      level: 5,
      levelValue: "6",
      resolution: 4891.96981024998,
      scale: 1.8489297737236e7
    },
    {
      level: 6,
      levelValue: "7",
      resolution: 2445.98490512499,
      scale: 9244648.868618
    },
    {
      level: 7,
      levelValue: "8",
      resolution: 1222.992452562495,
      scale: 4622324.434309
    },
    {
      level: 8,
      levelValue: "9",
      resolution: 611.4962262813797,
      scale: 2311162.217155
    },
    {
      level: 9,
      levelValue: "10",
      resolution: 305.74811314055756,
      scale: 1155581.108577
    },
    {
      level: 10,
      levelValue: "11",
      resolution: 152.87405657041106,
      scale: 577790.554289
    },
    {
      level: 11,
      levelValue: "12",
      resolution: 76.43702828507324,
      scale: 288895.277144
    },
    {
      level: 12,
      levelValue: "13",
      resolution: 38.21851414253662,
      scale: 144447.638572
    },
    {
      level: 13,
      levelValue: "14",
      resolution: 19.10925707126831,
      scale: 72223.819286
    },
    {
      level: 14,
      levelValue: "15",
      resolution: 9.554628535634155,
      scale: 36111.909643
    },
    {
      level: 15,
      levelValue: "16",
      resolution: 4.77731426794937,
      scale: 18055.954822
    },
    {
      level: 16,
      levelValue: "17",
      resolution: 2.388657133974685,
      scale: 9027.977411
    }
  ];
  var tileInfo = {
    rows: 256,
    cols: 256,
    dpi: 96,
    origin: {
      x: -2.00375083427892e7,
      y: 2.00375083427892e7,
      spatialReference: {
        wkid: 3857
      }
    },
    spatialReference: {
      wkid: 3857
    },
    lods: lods_tdt
  };
  
  export var webtilelayers = [
    {
      urlTemplate: tdtvecaddr,
      copyright: "天地图",
      id: "tdtvec",
      subDomains: ["t0", "t1", "t2"],
      tileInfo: tileInfo
    },
    {
      urlTemplate: tdtsataddr,
      copyright: "天地图",
      id: "tdtwx",
      subDomains: ["t0", "t1", "t2"],
      tileInfo: tileInfo
    },
    {
      urlTemplate: tdtcvaaddr,
      copyright: "天地图",
      id: "tdtcva",
      subDomains: ["t0", "t1", "t2"],
      tileInfo: tileInfo
    },
    {
      urlTemplate: osmcartourl,
      copyright: "OSM",
      id: "osm",
      subDomains: ["a", "b", "c"]
    }
  ];
  // webtilelayers.forEach(d=>{delete d.tileInfo})
  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == variable) {
        return pair[1];
      }
    }
    return false;
  }
  export let coordsmap = {};
  export async function getLayersData(coors, sr) {
    var option = {
      where: "1=1",
      f: "json",
      OutFields: "*",
      outSR: sr ? sr : "4326",
      geometry: JSON.stringify({
        xmin: coors[0],
        ymin: coors[1],
        xmax: coors[2],
        ymax: coors[3]
      })
    };
    var res = await $.post(url_ftserver + "/1/query", option);
    var resdata = JSON.parse(res);
    var projectids = "";
    var explorids = "";
    resdata.features.forEach(ele => {
      projectids += `'${ele.attributes["project_id"]}',`;
      explorids += `'${ele.attributes["explor_id"]}',`;
      coordsmap[
        ele.attributes["project_id"] +
          "~" +
          ele.attributes["explor_id"]
      ] = ele.geometry;
    });
    projectids = projectids.substr(0, projectids.length - 1);
    explorids = explorids.substr(0, explorids.length - 1);
  
    var option = {
      where: `project_id in (${projectids}) and explor_id in (${explorids})`,
      f: "json",
      OutFields: "*",
      orderByFields: "project_id,explor_id,layer_code"
    };
    res = await $.post(url_ftserver + "/10/query", option);
    var layersdata = JSON.parse(res);
    return layersdata;
  }
  
  function unique(arr) {
    return Array.from(new Set(arr));
  }
  
  export function calcBisect_surface(surface, xpos, ypos) {
    var points = [];
    // console.log(surface)
    surface.forEach(graphic => {
      // console.log(graphic)
      points = points.concat(calcBisect_tin(graphic.geometry, xpos, ypos));
    });
    points = unique(points);
    return points;
  }
  
  function calcBisect_tin(polygon, xpos, ypos) {
    var points = [];
    for (let i = 0; i <= 2; i++) {
      let pt = calcBisect_line(
        polygon.rings[i],
        polygon.rings[i + 1],
        xpos,
        ypos
      );
      // console.log(pt)
      if (pt) points.push(pt);
    }
    return points;
  }
  
  function calcBisect_line(p1, p2, xpos, ypos) {
    // console.log(p1,p2,xpos);
    if ((p1[0] < xpos && p2[0] > xpos) || (p1[0] > xpos && p2[0] < xpos)) {
      return [
        xpos,
        p1[1] + ((p2[1] - p1[1]) * (xpos - p1[0])) / (p2[0] - p1[0]),
        p1[2] + ((p2[2] - p1[2]) * (xpos - p1[0])) / (p2[0] - p1[0])
      ];
    } else return null;
  }
  export function calcSurface(
    datas,
    layeridx,
    type,
    sr,
    Graphic,
    graphicsLayer,
    coors,
    width = 12
  ) {
    var layerfts = datas.filter(
      ft => ft.attributes.layeridx == layeridx && ft.attributes.type == type
    );
    if (layerfts.length <= 2) return null;
    /** 插值 */
    let arr_x = layerfts.map(ft => ft.geometry.x);
    let arr_y = layerfts.map(ft => ft.geometry.y);
    let arr_z = layerfts.map(ft => ft.attributes.depth_btm);
    var model = "exponential";
    var sigma2 = 0,
      alpha = 100;
    var fitModel = kriging.train(arr_z, arr_x, arr_y, model, sigma2, alpha);
    console.log(fitModel);
    let arr_nx = [];
    let arr_ny = [];
    // var arr_nz = kriging.predict(arr_nx, arr_ny, fitModel);
    // console.log(arr_nz)
    console.log(coors);
    var grid = kriging.grid(
      turf.bboxPolygon(coors).geometry.coordinates,
      fitModel,
      width
    );
    console.log(grid);
    let xlen = (coors[2] - coors[0]) / width;
    let ylen = (coors[3] - coors[1]) / width;
    let ntfs = [];
    for (let i = 0; i < xlen; i++) {
      for (let j = 0; j < ylen; j++) {
        if (grid[i] && grid[i][j]) {
          ntfs.push({
            properties: { z: grid[i][j] },
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [coors[0] + width * i, coors[1] + width * j]
            }
          });
        }
      }
    }
  
    var tins = turf.tin(
      {
        type: "FeatureCollection",
        features: ntfs
      },
      "z"
    );
    //构造TIN
    // var tins = turf.tin(
    //   {
    //     type: "FeatureCollection",
    //     features: layerfts.map(ft => {
    //       return {
    //         properties: ft.attributes,//{depth_btm:ft.attributes.depth_btm},
    //         type: "Feature",
    //         geometry: {
    //           type: "Point",
    //           coordinates: [ft.geometry.x, ft.geometry.y]
    //         }
    //       };
    //     })
    //   },
    //   "depth_btm"
    // );
  
    //  console.log(layerfts.map(ft => { return { id: ft.attributes.explor_id, layeridx: ft.attributes.layeridx, type: ft.attributes.type, x: ft.geometry.x, y: ft.geometry.y, depth: ft.attributes.depth_btm } }), tins);// && console.log(i,comm.typelist[j],layerfts,tins);
    let c = randomColor();
    let surface = [];
    //构造featurelayer图层
    tins.features.forEach(ft => {
      var polygon = {
        type: "polygon", // autocasts as new Polygon()
        rings: ft.geometry.coordinates[0],
        spatialReference: { wkid: sr }
      };
      polygon.rings[0][2] = ft.properties.a;
      polygon.rings[1][2] = ft.properties.b;
      polygon.rings[2][2] = ft.properties.c;
      polygon.rings[3][2] = ft.properties.a;
      // console.log(polygon)
      var polygonGraphic = new Graphic({
        geometry: polygon,
        symbol: {
          // type: "picture-fill",  // autocasts as new PictureFillSymbol()
          // url: `./img/layer/${comm.typelist[j]}.png`,
          // width: "24px",
          // height: "24px",
          // outline: {
          //   style: "solid"
          // },
          type: "simple-fill", // autocasts as new SimpleFillSymbol()
          color: c, //[ 51,51, 204, 0.9 ],
          style: "solid",
          outline: {
            // autocasts as new SimpleLineSymbol()
            color: "white",
            width: 1
          }
        }
      });
      surface.push({ geometry: polygon });
      //   console.log(polygonGraphic);
      graphicsLayer.add(polygonGraphic);
    });
    return { surface, c };
  }
  function randomColor() {
    return [
      parseInt(Math.random() * 255),
      parseInt(Math.random() * 255),
      parseInt(Math.random() * 255),
      0.5
    ];
    var color = "#";
    for (var i = 0; i < 6; i++)
      color += parseInt(Math.random() * 16).toString(16);
    // return color;
  }
  
  export function combinelayers(layersdata, sr) {
    //合并同层
    var layersdata_combine = [];
    layersdata.features.forEach((ft, idx) => {
      if (idx > 0) {
        if (
          layersdata.features[idx - 1].attributes.project_id ==
            ft.attributes.project_id &&
          layersdata.features[idx - 1].attributes.explor_id ==
            ft.attributes.explor_id
        ) {
          if (
            layersdata.features[idx - 1].attributes.type != ft.attributes.type
          ) {
            layersdata_combine.push(layersdata.features[idx - 1]);
          } else {
          }
        } else {
          // layersdata_combine.push(layersdata.features[idx - 1]);
        }
        if (idx == layersdata.features.length - 1) {
          console.log(JSON.stringify(layersdata.features[idx - 1]));
          // layersdata_combine.push(ft);
        }
      }
    });
    layersdata.features = layersdata_combine;
    layersdata_combine.sort(
      (d1, d2) =>
        d1.attributes.project_id.localeCompare(d2.attributes.project_id) ||
        d1.attributes.explor_id.localeCompare(d2.attributes.explor_id) ||
        d1.attributes.layer_code.localeCompare(d2.attributes.layer_code)
    );
    //计算坐标、层顶
    layersdata_combine.forEach((ft, idx) => {
      //find layer position
      var pos =
        coordsmap[ft.attributes.project_id + "~" + ft.attributes.explor_id];
      if (!pos) return;
      ft.attributes.depth_btm = ft.attributes.depth_btm * -10;
      ft.attributes.depth_btm > 0 && console.log(JSON.stringify(ft));
      ft.geometry = {
        type: "point",
        x: pos.x,
        y: pos.y,
        z: ft.attributes.depth_btm
      };
      ft.spatialReference = { wkid: sr };
      //计算地层顶
      if (
        idx > 0 &&
        layersdata_combine[idx - 1].attributes.project_id ==
          ft.attributes.project_id &&
        layersdata_combine[idx - 1].attributes.explor_id ==
          ft.attributes.explor_id
      ) {
        ft.attributes.depth_top =
          layersdata_combine[idx - 1].attributes.depth_btm;
        ft.attributes.layeridx =
          layersdata_combine[idx - 1].attributes.layeridx + 1;
      } else {
        ft.attributes.depth_top = 0;
        ft.attributes.layeridx = 0;
      }
    });
    return layersdata_combine;
  }
  
  function merge(sname, sobj, tname, tobj) {
    let ret = {};
    if (sname) {
      for (let att in sobj) {
        ret[sname + "-" + att] = sobj[att];
      }
    } else {
      for (let att in sobj) {
        ret[att] = sobj[att];
      }
    }
    if (tname) {
      for (let att in tobj) {
        ret[tname + "-" + att] = tobj[att];
      }
    }
    return ret;
  }
  export function arrayJoin(sname, arr_s, tname, arr_t, fields) {
    let ret = [];
    arr_s.forEach(a_s => {
      /** 计算是否多对多 */
      let a_s_all = arr_s.filter(a => {
        let eq = true;
        fields.forEach(f => {
          if (a_s[f.f_s] != a[f.f_s]) {
            eq = false;
          }
        });
        return eq;
      });
      let ismulti = false;
      if (a_s_all.length > 1) {
        ismulti = true;
      }
  
      /** 左连接 */
      if (ismulti) {
        let a_idx = arr_t.findIndex(a_t => {
          let eq = true;
          fields.forEach(f => {
            if (a_s[f.f_s] != a_t[f.f_t]) {
              eq = false;
            }
          });
          return eq;
        });
        if (a_idx >= 0) {
          ret.push(merge(sname, a_s, tname, arr_t[a_idx]));
          arr_t.splice(a_idx, 1);
        } else {
          //   console.log('idx0',a_s)
          ret.push(merge(sname, a_s));
        }
      } else {
        let a_ts = arr_t.filter(a_t => {
          let eq = true;
          fields.forEach(f => {
            if (a_s[f.f_s] != a_t[f.f_t]) {
              eq = false;
            }
          });
          return eq;
        });
        //   console.log('filter',a_ts)
        if (a_ts.length > 0) {
          a_ts.forEach(a => {
            ret.push(merge(sname, a_s, tname, a));
          });
        } else {
          ret.push(merge(sname, a_s));
        }
      }
    });
    /** 右连接 */
    // arr_t.forEach(a_t => {
    //   let a_s = arr_s.find(a_s => {
    //     let eq = true;
    //     fields.forEach((f, idx) => {
    //       if (a_s[f.f_s] != a_t[f.f_t]) {
    //         eq = false;
    //       }
    //     });
    //     return eq;
    //   });
    //   if (!a_s) {
    //     ret.push(merge(tname, a_t));
    //   }
    // });
    return ret;
  }
  
  export async function netPing(url) {
    try {
      let res = await $.ajax({
        type: "GET",
        cache: false,
        url: url,
        data: ""
      });
      return true;
    } catch (e) {
      return false;
    }
  }
  
  let shiyantypes = {
    'CPT':8,
    'DPT':9,
    'PLT':14,
    'SLT':16,
    'SPT':17
  }
  let shiyannames = {
    'CPT':'静力触探试验成果表',
    'DPT':'圆锥动力触探试验成果表',
    'PLT':'地基载荷试验成果表',
    'SLT':'钻孔取样及土工试验表',
    'SPT':'标贯试验成果表'
  }
  
  async function getcols(table) {
    let res = await $.get(
      url_webback + "/api/metadata/" + table,
    );
    res = res.fields;
    const nocols = [
      "OBJECTID",
      "project_id",
      "explor_id",
      "layer_code",
    ];
    return res.filter((c) => nocols.indexOf(c.name) < 0);
  }
  
  let explorcolor={
    'qt':'#ff9900',
    'jl':'#4a86e8',
    'tj':'#00ffff',
    'lx':'#cc4125',
    'jb':'#6aa84f',
    'else':'#9900ff'
  }
  
  export default {
    // url_webserver,
    style_label,
    fetch_sync,
    post_async,
    // url_services,
    // url_ftserver,
    // getFields_explor,
    // tablefields_explor,
    formatData_JSON,
    getFields_layer,
    getFields,
    // fields_explor,
    getQueryVariable,
    typelist,
    getdict,
    getExplors,
    locale,
    lang,
    getData,
    getData0,
    shiyantypes,
    shiyannames,
    getcols,
    sqlpre,
    explorcolor,
  };